﻿<%@ page contentType="text/html;charset=UTF-8"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="com.tjtt.tdm.system.action.RoleAction"%>
<%@page import="com.tjtt.tdm.system.bean.Role"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page import="java.util.List"%>
<%@taglib prefix="s" uri="/struts-tags"%>


		
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>角色管理</title>     
        <%@ include file="../jslib/jquerylib.jsp" %>  
		<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/web/style/layout4.css" />
		<script type='text/javascript' src="<%=request.getContextPath() %>/jslib/jquery.form.js"></script>
		<link href="<%=request.getContextPath() %>/web/style/layout.css" type="text/css" rel="stylesheet"/>
        <link rel="stylesheet" href="<%=request.getContextPath() %>/jslib/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css"/>
		<script type="text/javascript" src="<%=request.getContextPath() %>/jslib/lhgdialog/lhgcore.lhgdialog.min.js?skin=mac"></script>
        <script type="text/javascript" src="<%=request.getContextPath() %>/jslib/ztree/js/jquery.ztree.core-3.5.js"></script>

	       <!-- 删除结果信息返回 -->
	    	<c:if test="${requestScope.message!=null}">
				<script type="text/javascript">
	  	 		     alert('<c:out value="${requestScope.message}"></c:out>');
	  	 		     window.close();	 	 		 
	  			</script>
	        </c:if>   
	     <style type="text/css">
			body, html{
			 overflow-x:hidden 
			}	
			 
		</style>
		
		<script type="text/javascript">
			var selectId = "" ;
			var treeObj;
			var parentid = "";
			var tree_sel = null;
			var rid = null;
			tree_sel_id="";
			var rid = "";
			var common_contextPath="<%=common_contextPath%>";
			var common_basePath="<%=common_basePath%>";
			var common_width = window.screen.width-0;
			var common_height = window.screen.height-400;
					
			$(function(){ 
			    $("#tabs").tabs({ 
			        //disabled:[1],//定义不可用元素 
			        selected:2 
			        }); 
			        //getRoleInfo230();
			       // $("#tabs").tabs("remove",3); 
			        //$("#tabs").tabs("add","tab-3","four"); 
			}) 
		
			//--查询名称 高亮 开始---------------------------------------------------------------------
			function focusKey(e) {
				if (key.hasClass("empty")) {
					key.removeClass("empty");
				}
			}
			function blurKey(e) {
				if (key.get(0).value === "") {
					key.addClass("empty");
				}
			}
			var lastValue = "", nodeList = [], fontCss = {};
			
			function searchNode(e) {
				var zTree = $.fn.zTree.getZTreeObj("tree");
				var value = $.trim(key.get(0).value);
				var keyType = "";
				keyType = "name";
				if (lastValue === value) return;
				lastValue = value;
				if (value === "") return;
				updateNodes(false);
				nodeList = zTree.getNodesByParamFuzzy(keyType, value);
				updateNodes(true);
	
			}
			function updateNodes(highlight) {
				var zTree = $.fn.zTree.getZTreeObj("tree");
				for( var i=0, l=nodeList.length; i<l; i++) {
					nodeList[i].highlight = highlight;
					zTree.updateNode(nodeList[i]);
				}
			}
			function getFontCss(treeId, treeNode) {
				return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
			}
			function filter(node) {
				return !node.isParent && node.isFirstNode;
			}
	
			var key;
			$(document).ready(function(){
				$.fn.zTree.init($("#tree"), setting, zNodes);
				key = $("#key");
				key.bind("focus", focusKey)
				.bind("blur", blurKey)
				.bind("propertychange", searchNode)
				.bind("input", searchNode); 
				var treeObj = $.fn.zTree.getZTreeObj("tree");
				var nodes = treeObj.getNodes();
				if (nodes.length>0) {
					treeObj.selectNode(nodes[0]);
					//设置选中节点后右边编辑内容的载入
					zTreeOnClick(event,"100",nodes[0],true);
					$("#pageFrom4").show();
					//getportlet(rid); 
				}
				 
				 
			});
			//--查询名称 高亮 结束---------------------------------------------------------------------
				
				
	<%
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
		RoleAction roleAction = (RoleAction)context.getBean("roleAction");
		List result = roleAction.getRoleTree();
		String treeNode = "";
		String roleId = "";
		String parentid = "" ;
		String rolename = "";
		String rolelabel = "";
		String roledesc = "";
		for(int i=0;i<result.size();i++){
			Role role = (Role)result.get(i);
			roleId = role.getRoleId().toString();
			parentid = role.getParentid().toString();
			rolename = role.getRolename();
			rolelabel = role.getRolelabel();
			roledesc = role.getRoledesc()==null?"":role.getRoledesc();
			if("100".equals(roleId)){
				treeNode +="{\"id\":"+roleId+",\"pId\":"+parentid+",\"name\":\""+rolename+"\",\"labels\":\""+rolelabel+"\",\"descs\":\""+roledesc+"\",\"open\":true},";	
			}else{
				treeNode +="{\"id\":"+roleId+",\"pId\":"+parentid+",\"name\":\""+rolename+"\",\"labels\":\""+rolelabel+"\",\"descs\":\""+roledesc+"\",\"open\":false},";	
			}			
		}
		String newTreeNode=treeNode.substring(0,treeNode.length()-1);	
		System.out.println(newTreeNode);
	%>
			var setting = {
				treeId:'tree',
				callback: {
						onClick: zTreeOnClick,
						beforeCollapse: beforeCollapse,
						beforeExpand: beforeExpand,
						onCollapse: onCollapse,
						onExpand: onExpand
					},
				view: {
					selectedMulti: false
				},
				data: {
					key: {
						title: "name"
					},
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "pId",
						rootPId: -1
					}
								
				},
				view: {
					fontCss: getFontCss
				}
			};
			function zTreeOnClick(event, treeId, treeNode) {
			    //alert(treeNode.id + ", " + treeNode.name+","+treeNode.pId);
			    tree_sel = treeNode;
			    rid=treeNode.id;
			    rid = tree_sel.id;
			    parentid = treeNode.pId;
			   	var rolename = treeNode.name;
			   	var labels = treeNode.labels;
			   	var descsss = treeNode.descs;
				document.getElementById("name").value = rolename;
				document.getElementById("labels").value = labels;
				document.getElementById("descs").value = descsss;
				document.getElementById("portletrole").value = rid;
				//document.getElementById("id").value = roleId;	
				reloadroleuser(rid);
				//tab-2					
				var urlss = common_contextPath+"/role/roleMenu.action?roleId="+rid
				jQuery("#mainframe").attr("src",urlss);	  
			    //tab-3
			    $("#tabs").show();
			    	getportlet(rid); 
			};
			
			function reloadroleuser(rid){
				jQuery("#fromTable").jqGrid('setGridParam',
					{	
						url:common_contextPath+'/role/queryUserList.action?roleid='+rid //查询该角色下没有的人员
					}).trigger("reloadGrid", [{page:1}]);	
				 jQuery("#toTable").jqGrid('setGridParam',
					{	
						url:common_contextPath+'/role/searchUsersByRole.action?roleid='+rid //查询该角色下所有人员
					}).trigger("reloadGrid", [{page:1}]);	
			}

//获取所有门户
			function getportlet(roleid){
				var params = {  
			        "roleId": roleid
				 };  
			   var actionUrl = "<%=request.getContextPath() %>/role/portletList.action";
			   $.ajax({  
			        url : actionUrl,  
			        type : "post", 
			        data : params,  
			        dataType : "text",  
			        cache : false,  
				    error : function(textStatus, errorThrown) {  
				        alert("系统ajax交互错误: " + textStatus.value);  
				    },
				    success : function(data, textStatus) {  
		           		 $("#portlet").html(data);
				    }
			 });
			}

			//-------添加角色----tree----
			function addRole(){
				//var obj = new Object();
				if(tree_sel==null){
					//alert(tree_sel);
					alert("请选择节点进行添加操作！");
				}
				$.dialog({
			        id:'cerify',
			        data:"{'parentid':"+tree_sel.id+",'parentName':'"+tree_sel.name+"'}",
			        
			        title:'角色添加', 
			        content:'url:<%=request.getContextPath() %>/system/rolesadd.jsp',
			        okVal:false,//确定按钮文字
			        cancelVal:false,//取消按钮文字
			        min:true, //是否显示最小化按钮
			        max:false,//是否显示最大化按钮
			        fixed:false,//开启静止定位
			        lock:true,//开启锁屏
			        focus:true,//弹出窗口后是否自动获取焦点（4.2.0新增）
			        time:null,//设置对话框显示时间
			        resize:true,//是否允许用户调节尺寸
			        drag:true,//是否允许用户拖动位置
			        cache:false,//是否缓存iframe方式加载的窗口内容页
			        width: '550px',
			        height: 350
	        	});
			}
			//-------修改角色--tree----
			function updateRole(){
				var obj = new Object();
				if(tree_sel==null){
					//alert(tree_sel);
					alert("请选择节点进行修改操作！");
				}if(tree_sel.pId == -1){
					alert("根节点不允许修改");
				}
				$.dialog({
			        id:'cerify',
			        data:"{'parentid':"+tree_sel.getParentNode().id+",'parentName':'"+tree_sel.getParentNode().name+"','roleId':'"+tree_sel.id+"','rolename':'"+tree_sel.name+"','rolelabel':'"+tree_sel.labels+"','roledesc':'"+tree_sel.descs+"'}",
			        title:'修改角色信息', 
			        content:'url:<%=request.getContextPath() %>/system/roleupdate.jsp',
			        okVal:false,//确定按钮文字
			        cancelVal:false,//取消按钮文字
			        min:true, //是否显示最小化按钮
			        max:false,//是否显示最大化按钮
			        fixed:false,//开启静止定位
			        lock:true,//开启锁屏
			        focus:true,//弹出窗口后是否自动获取焦点（4.2.0新增）
			        time:null,//设置对话框显示时间
			        resize:true,//是否允许用户调节尺寸
			        drag:true,//是否允许用户拖动位置
			        cache:false,//是否缓存iframe方式加载的窗口内容页
			        width: '550px',
			        height: 350
	        	});
			}
			
			 //ajax方法删除
	        function deleteRole(){
				 if(tree_sel == null){
						alert("请选择节点进行删除");
				}else if(tree_sel.pId == -1){
					alert("根节点不允许删除");
					return false;
				}else{
					if(!confirm("是否确认删除 ？")){
	                    return false;
 	                }				
					  var params = {  
				        "ids": tree_sel.id
					 }; 
				if(tree_sel.name=='系统管理员' || tree_sel.name=='安全保密管理员' || tree_sel.name=='安全审计管理员' || tree_sel.name == '系统角色'){
						alert("此项不能删除");
						return false;
	            }else{
	                rid = tree_sel.id;//获取选中行的id属性     
	  	                var actionUrl = "delRole.action?roleId="+rid;  
	  	                    $.ajax({  
	  	                        url : actionUrl,  
	  	                        type : "post", 
	  	                        dataType : "json",  
	  	                        cache : false,  
	  	                    error : function(textStatus, errorThrown) {  
	  	                        alert("系统ajax交互错误: " + textStatus.value);  
	  	                    },  
	  	                    success : function(data, textStatus) {  
	  	                    	if(typeof(data.ajaxResult)=='undefined'){
	  	                    	alert("角色下存在用户，或存在子节点，不允许删除！"); 
	  	                    	}
	  	                    	if(data.ajaxResult=='error'){
	  	                            alert("角色下存在用户，或存在子节点，不允许删除！"); 
	  	                            tree_sel = "" ;   
	  	                        }else if(data.ajaxResult=='success'){
	  	                            alert("删除成功！");    
	  	                            tree_sel = "" ;   
	  	                             location.reload();
	  	                        }
	  	                    }  
	  	                });
				}	
			  }				
	        }

	        //刷新
            function reload(){
                location.reload(); 
            } 
			
			var zNodes =[
					<%=newTreeNode%>
			];
		
			function showIconForTree(tetid, treeNode) {
				return !treeNode.isParent;
			};
			//展开/关闭按钮 开始-----------------------------------------------------------------------
			var log, className = "dark";
			function beforeCollapse(treeId, treeNode) {
				className = (className === "dark" ? "":"dark");
				showLog("[ "+getTime()+" beforeCollapse ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name );
				return (treeNode.collapse !== false);
			}
			function onCollapse(event, treeId, treeNode) {
				showLog("[ "+getTime()+" onCollapse ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name);
			}		
			function beforeExpand(treeId, treeNode) {
				className = (className === "dark" ? "":"dark");
				showLog("[ "+getTime()+" beforeExpand ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name );
				return (treeNode.expand !== false);
			}
			function onExpand(event, treeId, treeNode) {
				showLog("[ "+getTime()+" onExpand ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name);
			}
			function showLog(str) {
				if (!log) log = $("#log");
				log.append("<li class='"+className+"'>"+str+"</li>");
				if(log.children("li").length > 8) {
					log.get(0).removeChild(log.children("li")[0]);
				}
			}
			function getTime() {
				var now= new Date(),
				h=now.getHours(),
				m=now.getMinutes(),
				s=now.getSeconds(),
				ms=now.getMilliseconds();
				return (h+":"+m+":"+s+ " " +ms);
			}
	
			function expandNode(e) {
				var zTree = $.fn.zTree.getZTreeObj("tree"),
				type = e.data.type,
				nodes = zTree.getSelectedNodes();
				if (type.indexOf("All")<0 && nodes.length == 0) {
					alert("请先选择一个父节点");
				}
	
				if (type == "expandAll") {
					zTree.expandAll(true);
				} else if (type == "collapseAll") {
					zTree.expandAll(false);
				} else {
					var callbackFlag = $("#callbackTrigger").attr("checked");
					for (var i=0, l=nodes.length; i<l; i++) {
						zTree.setting.view.fontCss = {};
						if (type == "expand") {
							zTree.expandNode(nodes[i], true, null, null, callbackFlag);
						} else if (type == "collapse") {
							zTree.expandNode(nodes[i], false, null, null, callbackFlag);
						} else if (type == "toggle") {
							zTree.expandNode(nodes[i], null, null, null, callbackFlag);
						} else if (type == "expandSon") {
							zTree.expandNode(nodes[i], true, true, null, callbackFlag);
						} else if (type == "collapseSon") {
							zTree.expandNode(nodes[i], false, true, null, callbackFlag);
						}
					}
				}
			}
			//展开/关闭按钮  结束---------------------------------------------------------------------
			$(document).ready(function(){
				treeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
				$("#expandAllBtn").bind("click", {type:"expandAll"}, expandNode);
				$("#collapseAllBtn").bind("click", {type:"collapseAll"}, expandNode);
			}); 
			
			function getRoleInfo230(){
				 var params = {  
				    };  
				    var actionUrl = "<%=request.getContextPath() %>/role/getRoleInfo230.action";  
				    $.ajax({  
				        url : actionUrl,  
				        type : "post", 
				        data : params,  
				        dataType : "json",  
				        cache : false,  
				        error : function(textStatus, errorThrown) {  
				            alert("系统ajax交互错误: " + textStatus.value);  
				        },  
				        success : function(data, textStatus) {  
				        	if('null'!=data){
				        		document.getElementById("name").value =data.rolename;
								document.getElementById("labels").value = data.rolelabel;
								if('null'!=data.roledesc){
									document.getElementById("descs").value = data.roledesc;
								}else{
									document.getElementById("descs").value = "";
								}
				        	}else{
				        		document.getElementById("name").value = "";
								document.getElementById("labels").value = "";
								document.getElementById("descs").value = "";
				        	}
					     }  
			    });
			}
			

	   function saveUserToRole(){
		   var userIds = $("#toTable").jqGrid('getDataIDs') + "";
			if(tree_sel == null){
			   rid= 230;
			   tree_sel = rid;
				//alert("请选择节点进行操作!");
			}
			if(tree_sel.pId == -1){
				alert("根节点不允许分配人员!");
				return false;
			}
			
		   var params = {  
			        "roleId": rid,
			        "userid": userIds
				 };  
		   var actionUrl = "<%=request.getContextPath() %>/role/addUserOfRole.action";
		   $.ajax({  
		        url : actionUrl,  
		        type : "post", 
		        data : params,  
		        dataType : "json",  
		        cache : false,  
			    error : function(textStatus, errorThrown) {  
			        alert("系统ajax交互错误: " + textStatus.value);  
			    },
			    success : function(data, textStatus) {  
	           		if(data.ajaxResult=='success'){
		        		alert("角色分配人员成功！");  
		        		gridSearch();
		        	}else if(data.ajaxResult=='error'){
		        		alert("请为角色分配人员！");       
		        	}
			    }
		 });
	   }
			
	//---------------------tab2  --------------------------
    //授权 tab-2
    function changeRight(rid){      
         rid = tree_sel.id;//获取选中的id属性 
         //alert(rid);
        var urlss = "roleMenu.action?roleId="+rid
       // alert(urlss);
        jQuery("#mainframe").attr("src",urlss);
    }

    function saveRoleMenu(){
		var result = {
	 		failure:function(resp){
	 			var resText = resp.responseText;
				var result = Ext.util.JSON.decode(resText);
				Ext.MessageBox.alert("错误",result.result);
	 		},
	 		success:function(resp){
	 			var resText = resp.responseText;
	 			var result = Ext.util.JSON.decode(resText);
	 			if(result.success){
		 			alert("权限配制成功");
		 			window.close();
	 			}else{
	 				Ext.MessageBox.alert("错误","权限配制失败，请与管理员联系！");
	 			}
	 		}
	 	}
	 	var menuId = document.getElementsByName("menu");
		var menuIds = "";
		for(var i=0;i<menuId.length;i++){
			if(menuId[i].checked == true && menuId[i].value!=0){
				menuIds += menuId[i].value+",";
			}
		}
		Ext.Ajax.request({
		   url: 'saveRoleMenu.action',
		   method:'post',
		  
		   success: result.success,
		   failure: result.failure,
		   params: {menuIds: menuIds,roleId:document.getElementById("roleId").value}
		});	
	}
	function savePortlet(){
	   var params = {  
	        "roleId": rid,
	        "portletList": getSelectedPortlet()
		 };  
	   var actionUrl = "<%=request.getContextPath() %>/role/updatePortlet.action";
	   $.ajax({  
	        url : actionUrl,  
	        type : "post", 
	        data : params,  
	        dataType : "json",  
	        cache : false,  
		    error : function(textStatus, errorThrown) {  
		        alert("系统ajax交互错误: " + textStatus.value);  
		    },
		    success : function(data, textStatus) {
			    if(data.ajaxResult=='success'){
			    	alert("保存成功！");
			    }  
		    }
	 });
	}
	function getSelectedPortlet(){
		var str="";  
				 $("input[name='portletList']:checkbox").each(function(){ 
	                if($(this).attr("checked")){
	                    str += $(this).val()+","
	                }
	            });
	    return str; 
	}

	
	//------------人员左右选  start--------------------------------------------------------------------------//
		  $(document).ready(function(){
                $("#fromTable").jqGrid({
                    url:'<%=request.getContextPath()%>/role/queryUserList.action',
                    datatype: "json",
                    height: 380,
                    width: 300, 
                    colNames:["用户id","用户名称","ordid","部门名称"],
                    colModel:[
                        {name:'userid',index:'userid',key:true,hidden:true},
						{name:'username',index:'username',width:100},
						{name:'org_id',index:'org_id',width:40,hidden:true},
						{name:'org_name',index:'org_name',width:144}
                    ],   
                    shrinkToFit:false,
                    sortname:'org_id',
                    sortorder:'desc',
                    viewrecords:false,
					multiselect: true, // 是否显示复选框
					gridview: true,  //提升速度
					rownumbers: true,
					//pagerpos : "no",//不显示分页
					//rowNum:500,//显示500条数据
					rowNum:10,
					ondblClickRow : function(rowid){
			            var row = $("#fromTable").jqGrid('getRowData',rowid);
			            $("#toTable").jqGrid('addRowData',rowid,row);
			            $("#fromTable").jqGrid('delRowData',rowid);
			        },
					//rowList:[15,20,50,200,500],
					toolbar: [false,"top"],
					jsonReader: {
						root:"rows",		// 数据行（默认为：rows）
						page: "page",  	// 当前页
						total: "total",  // 总页数
						records: "records",  // 总记录数
						repeatitems : false		// 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
					},
					prmNames:{rows:"rows",page:"page",sort:"sidx",order:"sord",search:"search"},
					postData: {
						toIds:request('producttype')
					},
					pager:"#fromPager",
					caption: "用户列表"
                });
                 jQuery("#fromTable").jqGrid('navGrid','#fromPager',{add:false,edit:false,del:false,search:false,refresh:false});
         //已选用户
         $("#toTable").jqGrid({
                    url:'<%=request.getContextPath() %>/role/searchUsersByRole.action?temp='+Math.round(Math.random()*10000)+'&roleid=230',
                    datatype: "json",
                    height: 380,
                    width: 301,  
                    colNames:["用户id","用户名称","ordid","部门名称"],
                    colModel:[
                        {name:'userid',index:'userid',key:true,hidden:true},
						{name:'username',index:'username',width:100},
						{name:'org_id',index:'org_id',width:40,hidden:true},
						{name:'org_name',index:'org_name',width:144}
                    ],   
                    shrinkToFit:false,
                    sortname:'org_id',
                    sortorder:'desc',
                    viewrecords:false,
					multiselect: true, // 是否显示复选框
					gridview: true,  //提升速度
					rownumbers: true,
					//pagerpos : "no",//不显示分页
					//rowNum:500,//显示500条数据
					rowNum:50,
					ondblClickRow : function(rowid){
			            var row = $("#toTable").jqGrid('getRowData',rowid);
			            $("#fromTable").jqGrid('addRowData',rowid,row);
			            $("#toTable").jqGrid('delRowData',rowid);
			        },	
					//rowList:[15,20,50,200,500],
					toolbar: [false,"top"],
					jsonReader: {
						root:"rows",		// 数据行（默认为：rows）
						page: "page",  	// 当前页
						total: "total",  // 总页数
						records: "records",  // 总记录数
						repeatitems : false		// 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
					},
					prmNames:{rows:"rows",page:"page",sort:"sidx",order:"sord",search:"search"},
					postData: {
						toIds:request('producttype')
					},
					pager:"#toPager",
					caption: "已选角色下人员"
                });    
         /*****************以下部分为选择与取消*****************/

    $("#to").click(function(){
        var s = $("#fromTable").jqGrid('getGridParam','selarrrow')+"";
        //var to = $("#toTable").jqGrid('getDataIDs')+"";
        if(s){
            $.ajax({
					type: "POST",
					async: false,//取消异步提交
					url: '<%=request.getContextPath() %>/system/userRoleAction!addUserRole.action?toids='+s+'&roleid='+document.getElementById("portletrole").value,
					dataType: "json",
					success : function(data, textStatus) {  
						var rid = document.getElementById("portletrole").value;
						reloadroleuser(rid);
					}
			});
		}
    });
	    
	    $("#toAll").click(function(){
	        var s = $("#fromTable").jqGrid('getDataIDs')+"";
	        var to = $("#toTable").jqGrid('getDataIDs')+"";
	        if(s){
	            $.ajax({
					type: "POST",
					async: false,//取消异步提交
					url: '<%=request.getContextPath() %>/system/userRoleAction!addUserRole.action?toids='+s+'&roleid='+document.getElementById("portletrole").value,
					dataType: "json",
					success : function(data, textStatus) {  
						var rid = document.getElementById("portletrole").value;
						reloadroleuser(rid);
					}
				});
	        }
	    });
	    
	    $("#from").click(function(){
	        var s = $("#toTable").jqGrid('getGridParam','selarrrow')+"";
	        var to = $("#fromTable").jqGrid('getDataIDs')+"";
	        if(s){
	            $.ajax({
					type: "POST",
					async: false,//取消异步提交
					url: '<%=request.getContextPath() %>/system/userRoleAction!delUserRole.action?toids='+s+'&roleid='+document.getElementById("portletrole").value,
					dataType: "json",
					success : function(data, textStatus) {  
						var rid = document.getElementById("portletrole").value;
						reloadroleuser(rid);
					}
				});
	        }
	    });
	    
	    $("#fromAll").click(function(){
	        var s = $("#toTable").jqGrid('getDataIDs')+"";
	        var to = $("#fromTable").jqGrid('getDataIDs')+"";
	        if(s){
	            $.ajax({
					type: "POST",
					async: false,//取消异步提交
					url: '<%=request.getContextPath() %>/system/userRoleAction!delUserRole.action?toids='+s+'&roleid='+document.getElementById("portletrole").value,
					dataType: "json",
					success : function(data, textStatus) {  
						var rid = document.getElementById("portletrole").value;
						reloadroleuser(rid);
					}
				});
	        }
	    });
        
         //确定按钮
        $("#entry").click(function(){
            var result =[];
            var s = $("#toTable").jqGrid('getDataIDs')+"";
	        if(s){
	           var arr = s.split(",");
	           for(var i=0;i<arr.length;i++){
	               var id = arr[i];
	               var row = $("#toTable").jqGrid('getRowData',id);
	               result.push(row);
	           }
	       }
	        window.returnValue = result;
	        window.close();
   		 });
    });

		  //查询
          function gridSearch(){
                var orgId =  $.trim($("#orgId").val());
			    var username = $.trim($("#username").val());
			    var userIds = "";
			    var toIds = $("#toTable").jqGrid('getDataIDs') + "";
				if (toIds) {
					var ids = toIds.split(",");
					for ( var i = 0; i < ids.length; i++) {
						var id = ids[i];
						var row = $("#toTable").jqGrid('getRowData', id);
						userIds += row.userid + ",";
					}
				}
				if (userIds.length > 0) {
					userIds = userIds.substring(0, userIds.length - 1);
				}
				
			    var params = {
			    	"orgId" : encodeURIComponent($.trim(orgId)),
			        "username" : encodeURIComponent($.trim(username)),
			        "userIds" : userIds
			    };
			    
			    var postData = $("#fromTable").jqGrid("getGridParam", "postData");
			    $.extend(postData, params);  //(9)将postData中的查询参数覆盖为空值
			    $("#fromTable").jqGrid('setGridParam',
			    {
						url:common_contextPath+'/role/queryUserList.action?roleid='+rid
				}).trigger("reloadGrid", [{page:1}]); 
          }     
          
          //清空按钮  
         function resetquery()
         {
           jQuery("#username").val("");
           jQuery("#orgId").val("");
           jQuery("#citySel").val("--请选择--"); 
         }
		   /**
			 * 获取URL参数
			 * @param {} paras 参数名
			 * @return {String}
			 */
			function request(paras)
			{ 
			    var url = location.href; 
			    var paraString = url.substring(url.indexOf("?")+1,url.length).split("&"); 
			    var paraObj = {} 
			    for (i=0; j=paraString[i]; i++){ 
			    	paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length); 
			    } 
			    var returnValue = paraObj[paras.toLowerCase()]; 
			    if(typeof(returnValue)=="undefined"){ 
			    	return ""; 
			    }else{ 
			    	return returnValue; 
			    } 
			}

	//------------人员左选右选 end--------------------------------------------------------------------------//
    //====================组织机构=========================//
      //下拉树选择组织
	       function beforeClick(treeId, treeNode) {
	           var check = (treeNode && !treeNode.isParent);
	          // if (!check) alert("请选择具体的组织机构");
	           return check;
	       }
        
	        function onClick(e, treeId, treeNode) {
	            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	            nodes = zTree.getSelectedNodes(),
	            v = "";
	            o = "";
	            nodes.sort(function compare(a,b){return a.id-b.id;});
	            for (var i=0, l=nodes.length; i<l; i++) {
	                v += nodes[i].name + ",";
	                o += nodes[i].id + ",";
	            }
	            if (v.length > 0 ) v = v.substring(0, v.length-1);
	            if (o.length > 0 ) o = o.substring(0, o.length-1);
	            var cityObj = $("#citySel");
	            var orgId = $("#orgId");
	            orgId.attr("value",o);
	            cityObj.attr("value", v);
	            hideMenu();
	        }
         	var treeIsLoad = false;
	        function showMenu() {
	            if(!treeIsLoad){
	                showOrgTree();
	            }    
	           
	            var cityObj = $("#citySel");
	            var cityOffset = $("#citySel").offset();
	            $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
	
	            $("body").bind("mousedown", onBodyDown);
	        }
	        function hideMenu() {
	            $("#menuContent").fadeOut("fast");
	            $("body").unbind("mousedown", onBodyDown);
	        }
	        function onBodyDown(event) {
	            if (!(event.target.id == "citySel" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
	                hideMenu();
	            }
	        }
        
        	function showOrgTree(){
	            treeIsLoad = true;
	            var setting = {
	                treeId:"orgTree",
	                view: {
	                    dblClickExpand: false
	                },
	                data: {
	                    simpleData: {
	                        enable: true
	                    }
	                },
	                callback: {
	                   // beforeClick: beforeClick,
	                    onClick: onClick
	                }
            };
            var zNodes;
            $.ajax({  
                   url : common_contextPath+"/organization/searchAllOrg.action",  
                   type : "post", 
                   dataType : "json",  
                   cache : false,  
                   async:false,
                   error : function(textStatus, errorThrown) {  
                       alert("系统ajax交互错误: " + textStatus.value);  
                   },  
                   success : function(data, textStatus) {
                      zNodes = data;
                      $.fn.zTree.init($("#treeDemo"), setting,zNodes);
                   } 
               });             
        	}  
    //============================================//
    </script>
	</head>
	<body><!--=============== tree=====================================  -->
		
		<table width="100%"  border="0" cellpadding="0" cellspacing="0">
			<tr>
				 <td height="379" width="260" valign="top" style="background: #FFFFFF; border: #aaaaaa solid 1px;">
					<div style="font-size:13px;height:30px;padding-top:5px;padding-left:5px;background-image: url(images/tree_l_sc_bg.gif);background-repeat:repeat-x;">角色名称：
						<input type="text" id="key" name="role.rolename" value="" class="empty" style="width:150px; height:16px; line-height:20px;"  />
					</div>
					<div style="font-size:13px;height:30px;padding-top:5px; text-align:center;background-image: url(images/tree_l_sc_bg.gif);background-repeat:repeat-x;">
	                	<input type="button" class="button_b" onclick="addRole()" name="Submit4" value="添加" style="width:70px; margin-left:5px;"/>
						<input type="button" class="button_b" onclick="updateRole()" name="Submit4" value="修改"  style="width:70px;"/>
						<input type="button" class="button_b" onclick="deleteRole()" name="Submit4" value="删除"  style="width:70px;"/>
						<%--<input id="role_query" type='button' value='授权' onclick='authorize()' class='button_b' />  --%>
						</div>
					<div style="background-image: url('<%=request.getContextPath() %>/jslib/ztree/img/titlie.gif'); background-repeat:repeat-x;height: 20px; width: 100%; padding-top:5px;">
						<span style="margin-left:20px;" >
						    <img onclick="return false;"  src="../jslib/ztree/img/add.png" alt="展开" title="点击展开所有节点"  id="expandAllBtn"/>
						</span>
						<span >
							<img onclick="return false;" src="../jslib/ztree/img/delete.gif"  alt="闭合" title="点击关闭所有节点" id="collapseAllBtn"/>
						</span>	
					</div>
					<div style="WIDTH: 260px; HEIGHT: 480px; OVERFLOW: auto; scrollbar-3dlight-color: #595959; scrollbar-arrow-color: #FFFFFF; scrollbar-base-color: #CFCFCF;scrollbar-darkshadow-color:#FFFFFF; scrollbar-face-color: #CFCFCF; scrollbar-highlight-color: #FFFFFF; scrollbar-shadow-color: #595959">
						<div id="treeList" class="dtree">
							<ul id="tree" class="ztree" style="width:230px; overflow:auto;"></ul>
						</div>
					</div>
				</td>
				<td valign="top" style="padding-left:10px;background-color:#eaeaea;">
					<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<tr>
<td>					
<div id="tabs" style="height:600px;"> 
	<ul style="border-top:0px;border-left:0px;border-right:0px;"> 
	<li><a href="#tab-1">角色基本信息</a></li> 
	<li><a href="#tab-2">授权菜单</a></li> 
	<li><a href="#tab-3">人员</a></li> 
	<li><a href="#tab-4">首页门户</a></li> 
	</ul> 
	<!-- 授权 -->
	<div id="tab-2" style="padding:8px;">
	<%--首先  加载出来的是 所有的菜单  然后根据所选角色显示该角色权限 --%>
		<iframe  src="" width="100%" height="550" frameborder="0" id="mainframe"> </iframe>
	</div> 	
	<!-- 角色基本信息 -->
	<div id="tab-1">
		<form action="" id="pageFrom" name="" method="post" >
			<input type="hidden" id="parentid" name="parentid"/>
			<input type="hidden" id="roleId" name="roleId"/>
			<table  width="100%" border="0" align="center" cellpadding="5" cellspacing="5" class="formTableNew">								
				<tr>
					<td align="right">角色名称：</td>
					<td align="left">
						<div class="div">
						<input id="name" name="rolename" value=""  style="width:80%;" readonly="readonly" onkeydown="if(event.keyCode==8)return false;"/>
						</div>
					</td>
				</tr>
				<tr>
					<td align="right">角色标识：</td>
					<td >
						<div class="div">
                         <select name="rolelabel" id="labels"  style="width:83%;" disabled="disabled" onkeydown="if(event.keyCode==8)return false;">
                          		<option value="ROLE_OPERATOR">操作员</option>
                          		<option value="ROLE_SYSADMIN">系统管理员</option>
                                <option value="ROLE_MAINTENANCE">研究员</option>   
                                <option value="ROLE_ADMIN">用户管理员</option>
                         </select>                         
                        </div>
                    </td>
				</tr>
				<tr>
					<td align="right">
						角色描述：
					</td>
					<td >
						<div class="div">
							<textarea rows="4" cols="50" id="descs" name="roledesc" style="width:80%;" readonly="readonly" onkeydown="if(event.keyCode==8)return false;"></textarea>
						</div>
					</td>
				</tr>
			</table>	
		</form>
	</div> 
	
	
	<!-- 人员 -->
	<div id="tab-3" style="padding:8px;">	
	
		<div id="search"  style="float: left">
		<table border="0" cellpadding="4" cellspacing="1" align="center" width="100%">
			<tr>
				<td align="left">用户名称:</td><td class="td_value"><input type="text" id="username" name="username" maxlength="20" style="width: 160px;"/></td>
				<td align="left">部门名称:</td>
				<td width="12%">
		             <input type="hidden" id="orgId" name="orgId" />
                     <input id="citySel" name="orgNameLabel" type="text"  readonly="readonly" value="--请选择--" style="width: 160px;  align:left; height: 20px; border: 1px #cccccc solid; background: url(img/xia_l.png) no-repeat right center; background-color:#FFFFFF;" onclick="showMenu();" />
                      	 <div id="menuContent" class="menuContent"
                           style="display: none; position: absolute;z-index:10000; background:#f0f6e4; border:1px solid #617775; overflow-y:auto; overflow-x:auto;width:180px;">
                             <ul id="treeDemo" class="ztree"
                               style="margin-top: 0; width: 170px; height: 200px;z-index:10000;">
                             </ul>
                        </div>		                        
		      </td>
											
				<td>
					<input type="button" class="button_b" value="查&nbsp;询" onclick="gridSearch()"/>
					<input type="button" class="button_b" value="清&nbsp;空" onclick="resetquery()"/>
				</td>
			</tr>
		</table>		
	</div>
	
	  
    <div style="float: left">
        <table id='fromTable'></table><div id='fromPager'></div>
    </div>
    <div style="width:45px;height:200px;float:left;text-align: center;padding-top: 100px;">
        <button id="to" class="button_b" style="padding-left:6px;padding-right:6px;">&nbsp;&nbsp;&gt;</button><br />
        <button id="toAll" class="button_b" style="padding-left:6px;padding-right:6px;">&gt;&gt;</button><br /><br />
        <button id="from" class="button_b" style="padding-left:6px;padding-right:6px;">&nbsp;&nbsp;&lt;</button><br />
        <button id="fromAll" class="button_b" style="padding-left:6px;padding-right:6px;">&lt;&lt;</button><br />
    </div>
    <div style="float:left">
        <table id='toTable'></table><div id='toPager'></div>
    </div>
    <div style="clear: both;text-align: center; hight:40px;padding-top:16px;display:none;">
        <button id="entry" class="button_b" onclick="saveUserToRole()">确&nbsp;定</button>
        <!--<button id="center" class="button_b">取&nbsp;消</button>  -->
    </div>
	</div> 
	<div id="tab-4" style="padding:8px;">	
		<div id="tab4">
			<form action="" id="pageFrom4" name="" method="post" >
				<input type="hidden" id="portletrole" name="portletrole"/>
				<table  width="100%" border="0" align="center" cellpadding="5" cellspacing="5" class="formTableNew">								
					<tr>
						<td align="right">首页门户：</td>
						<td algin="left">
							<div id="portlet">
								
							</div>
						</td>
					</tr>
					<tr>
						<td align="center" colspan="2">
							<input type="button" id="saveBtn" onclick="savePortlet()" class="form_bt_orange" value="保存"/>
						</td>
					</tr>
				</table>
			</form>
		</div>
		
	</div>
</div> 
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</body>

</html>
